import axios from 'axios'
import qs from 'qs'
import merge from 'lodash/merge'
import utils from '@/plugins/utils'
import { Message } from 'element-ui'

const http = axios.create({
  baseURL: window.TAG_CONFIG['baseUrl'],
  timeout: 1000 * 30,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  paramsSerializer: function(params) {
    return qs.stringify(params, { allowDots: true, indices: !!params.d })
  }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(
  config => {
    // 请求头带上token
    if (window.localStorage.getItem('token')) {
      config.headers['auth-token'] = window.localStorage.getItem('token')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截
 */
http.interceptors.response.use(
  response => {
    if (response.data.code !== '0') {
      console.log('请求发生错误，错误代码：' + response.data.code)
      console.log('错误信息：' + response.data.msg)
    }
    if (response.headers['auth-token']) {
      window.localStorage.setItem('token', response.headers['auth-token'])
    }
    return response
  },
  error => {
    if (error.response.status === 401) {
      // 401, token失效
      utils.clearLoginInfo()
      utils.sysOut()
    }
    if (error.response.status === 403) {
      // 403, 没有权限
      Message.error('没有进行该操作的权限')
    }
    if (error.response.status === 504) {
      // 504，后端Nginx连接超时
      Message.error('连接超时，请稍后再试')
    }
    return Promise.reject(error)
  }
)

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.setUrl = (actionName, domain = 'baseUrl') => {
  return window.TAG_CONFIG[domain] + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.setParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    t: new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.setData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    t: new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default http
